package com.smh;

import org.junit.jupiter.api.Test;

import java.util.Iterator;

/**
 * @author shiminghui
 * @date 2025/2/15 15:28
 * @description: TODO
 */
public class _017_栈_数组 {

    @Test
    public void test1() {
        ArrayStack<Integer> stack = new ArrayStack<>();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        for (Integer i : stack) {
            System.out.println(i);
        }
    }

    public static class ArrayStack<T> implements Iterable<T> {
        private T[] data;
        private int capacity;
        private int top;
        private int size;

        public ArrayStack(int capacity) {
            this.capacity = capacity;
            this.data = (T[]) new Object[capacity];
            this.top = -1;
            this.size = 0;
        }

        public ArrayStack() {
            this(10);
        }

        public boolean push(T data) {
            if (size >= capacity) {
                return false;
            }
            this.data[++top] = data;
            size++;
            return true;
        }

        public T pop() {
            if (top == -1) {
                return null;
            }
            T data = this.data[top--];
            size--;
            return data;
        }

        public T peek() {
            if (top == -1) {
                return null;
            }
            return this.data[top];
        }

        public boolean isEmpty() {
            return top == -1;
        }

        public boolean isFull() {
            return size >= capacity;
        }

        public Iterator<T> iterator() {
            return new Iterator<T>() {
                private int index = top;

                @Override
                public boolean hasNext() {
                    return index >= 0;
                }

                @Override
                public T next() {
                    return data[index--];
                }
            };
        }
    }

}
